import { useEffect, useRef, useState } from "react";
import styles from "./styles.module.less";
import { setLog, useCollectStore } from "@/store/collectStore";
import { Button, Input, InputNumber, Tag, Transfer } from "antd";
import type { TransferProps } from "antd";
import { useShallow } from "zustand/react/shallow";
import { Icon } from "@iconify-icon/react";
import { http } from "@/constant/status";
import {
  GetCollectScriptList,
  ReadCharacterCoord,
  RunningScript,
  StopTask,
} from "@go/app/App";
import { UnregisterHotkey } from "@go/app/HotkeyApp";
import LogInfo from "@/components/log-info";
import { useMainStore } from "@/store/mainStore";
import { EventsOff, EventsOn } from "@runtime";
import audioStart from "@/assets/audio/Speech On.wav";
import audioStop from "@/assets/audio/Speech Sleep.wav";

const Collect = () => {
  const [selectedKeys, setSelectedKeys] = useState<TransferProps["targetKeys"]>(
    []
  );
  const [total, setTotal] = useState(0);
  const totalRef = useRef(0);
  totalRef.current = total;
  const { currentHwnd, currentCoordObj } = useMainStore(
    useShallow((state) => ({
      currentHwnd: state.currentHwnd,
      currentCoordObj: state.currentCoordObj,
    }))
  );
  const { collectSourceList, collectTargetList, isInput, isStart, log } =
    useCollectStore(
      useShallow((state) => ({
        collectSourceList: state.collectSourceList,
        collectTargetList: state.collectTargetList,
        isInput: state.isInput,
        isStart: state.isStart,
        log: state.log,
      }))
    );
  const disabledStart = useRef(false);
  const firstPath = useRef("");
  disabledStart.current =
    isStart || isInput || collectTargetList.length === 0 || !currentHwnd;
  firstPath.current = collectTargetList[0] || "";
  const onChange: TransferProps["onChange"] = (
    nextTargetKeys,
    direction,
    moveKeys
  ) => {
    useCollectStore.setState({
      collectTargetList: nextTargetKeys,
    });
  };

  const onSelectChange: TransferProps["onSelectChange"] = (
    sourceSelectedKeys,
    targetSelectedKeys
  ) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  // 开始任务
  const startTask = async () => {
    const audio = new Audio(audioStart);
    audio.play();
    useCollectStore.setState({
      isStart: true,
      log: "",
    });
    RunningScript(firstPath.current, "scriptCollect", totalRef.current);
  };

  // 停止任务
  const stopTask = async () => {
    const audio = new Audio(audioStop);
    audio.play();
    await StopTask("scriptCollect");
    useCollectStore.setState({
      isStart: false,
    });
    useMainStore.setState({
      currentCoordObj: { x: 0, y: 0, z: 0 },
    });
  };

  const getCollectList = async () => {
    const res = await GetCollectScriptList();
    console.log(res);
    if (res.code == http.StatusOK) {
      useCollectStore.setState({
        collectSourceList: res.data || [],
      });
    }
  };

  useEffect(() => {
    getCollectList();
  }, []);

  useEffect(() => {
    getCollectList();
    EventsOn("onScript", (state: boolean) => {
      console.log("onScript", state);
      if (state) {
        if (disabledStart.current) {
          setLog("当前状态不允许开始任务");
          return;
        }
        startTask();
      } else {
        stopTask();
      }
    });
    return () => {
      EventsOff("onScript");
    };
  }, []);

  useEffect(() => {
    const getCoordData = async () => {
      try {
        if (isStart) {
          const res = await ReadCharacterCoord();
          useMainStore.setState({ currentCoordObj: res.data || {} });
        }
      } catch {}
    };
    const interval = setInterval(getCoordData, 1500);
    return () => clearInterval(interval);
  }, [isStart]);

  return (
    <div className={styles.container}>
      <div className={styles.operations}>
        <Button
          icon={<Icon icon="material-symbols:folder-open-outline" width={14} />}
          iconPosition="end"
        >
          打开目录
        </Button>
        {isInput ? (
          <Button
            color="danger"
            variant="outlined"
            icon={<Icon icon="mingcute:pause-fill" width={14} />}
            iconPosition="end"
            onClick={() => {
              console.log("停止采集");
              useCollectStore.setState({
                isInput: false,
              });
            }}
          >
            停止采集
          </Button>
        ) : (
          <Button
            icon={<Icon icon="radix-icons:resume" width={14} />}
            iconPosition="end"
            disabled={isStart}
            onClick={() => {
              console.log("开始采集");
              useCollectStore.setState({
                isInput: true,
              });
            }}
          >
            开始采集
          </Button>
        )}
      </div>
      <div className={styles.scriptContent}>
        <Transfer
          dataSource={collectSourceList}
          titles={["文本列表", "任务列表"]}
          targetKeys={collectTargetList}
          selectedKeys={selectedKeys}
          onChange={onChange}
          oneWay
          operations={["添加", "移除"]}
          onSelectChange={onSelectChange}
          render={(item) => item.title}
          locale={{
            itemUnit: "项",
            itemsUnit: "项",
          }}
          style={{ flex: 1 }}
          listStyle={{
            width: "100%",
          }}
          disabled={isStart}
        />
        <div className={styles.scriptOperations}>
          <InputNumber
            value={total}
            placeholder="次数"
            controls={false}
            autoComplete="off"
            size="small"
            min={0}
            precision={0}
            style={{ width: "60px" }}
            onChange={(value) => setTotal(value as number)}
          />
          <Button disabled={disabledStart.current} onClick={startTask}>
            开始
          </Button>
          <Button
            color="danger"
            variant="outlined"
            disabled={!isStart}
            onClick={stopTask}
          >
            停止
          </Button>
        </div>
      </div>
      <div style={{ margin: "10px 60px 0 0", textAlign: "right" }}>
        {currentHwnd && (
          <Tag bordered={false} color="processing">
            {`${currentCoordObj.x}, ${currentCoordObj.y}`}
          </Tag>
        )}
      </div>
      <LogInfo value={log} />
    </div>
  );
};

export default Collect;
